package qs.openxt.libs.plugins;

import android.os.Handler;
import android.os.Message;
import android.widget.Toast;

import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.json.JSONArray;
import org.json.JSONException;

import java.io.File;

import qs.openxt.libs.util.ActivityUtil;
import qs.openxt.libs.util.PictureUtil;
import qs.openxt.libs.util.StringUtil;

/**
 * 语音识别
 * @author 颖杰_2
 *
 */
public class PreviewPicturePlugins extends CordovaPlugin{
	private CallbackContext callbackContext;
	private Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
				case 1:{
					callbackContext.success((String)msg.obj);
					break;
				}
                case 2: {
                    Toast.makeText(cordova.getActivity(), (String) msg.obj, Toast.LENGTH_LONG).show();
                    break;
                }
			default:
				break;
			}
		};
	};

    private void sendMessage(int what, String mMessage){
        Message msg = new Message();
        msg.what = what;
        msg.obj = mMessage;
        mHandler.sendMessage(msg);
    }

	public boolean execute(String action, final JSONArray args, final CallbackContext callbackContext) throws JSONException {
		this.callbackContext = callbackContext;
		if ("doPreviewPicture".equals(action)) {
            String path = args.optString(0);
            if(StringUtil.isNull(path)){
                sendMessage(2, "请传人图片地址");
            }else if(!new File(path).exists()){
                sendMessage(2, "图片不存在");
            }else{
                sendMessage(1, PictureUtil.bitmapToString(path, 100));
            }
			return true;
		}
		return false;
	}
}
